// pages/activityCenter/question.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "问卷", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    questionList: [],

    mySf: '',
    openid: '',
    shareTitle: '',
    shareImg: '',
    tipsContent: '',
    is_register: 0,
    id: 0,
    activityInfo: [],
    tid: 0,
    sid: 0,
    kid:0,
    people_number: 0,
    team: '',
    room_number: '',
    remark: '',
    //time: '',
    //sjd: '',
    checkBoxList: [],
    timeInfo:''//用户报名的时间日期信息
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },

  //数字输入值
  numTap(e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    that.setData({
      ['questionList[' + idx + '].value']: e.detail.value
    });
  },

  //数字输入值
  inputBlur(e) {
    if (parseInt(e.detail.value) >= 0) {
      var that = this;
      var idx = e.currentTarget.dataset.idx;
      that.setData({
        ['questionList[' + idx + '].value']: e.detail.value
      });
    }
  },

  //问答题
  textareaChange(e) {
    let len = e.detail.value.length;
    var idx = e.currentTarget.dataset.idx;
    this.setData({
      ['questionList[' + idx + '].limitNum']: len,
      ['questionList[' + idx + '].value']: e.detail.value
    });
  },

  //单选
  radioChange(e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var chooseText = this.data.questionList[idx].chooseList[value - 1].answer;
    if (chooseText == "其他" || chooseText == '其它') {
      that.setData({
        ['questionList[' + idx + '].value']: value,
        ['questionList[' + idx + '].reply']: true
      });
    } else {
      that.setData({
        ['questionList[' + idx + '].value']: value,
        ['questionList[' + idx + '].reply']: false
      });
    }
  },

  //多选题
  checkboxChange(e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    var value = e.detail.value;
    that.setData({
      checkBoxList: value, //单个选中的值
    })
    var checkBoxList = that.data.checkBoxList;
    if (checkBoxList.indexOf("其他") > -1 || checkBoxList.indexOf("其它") > -1) {
      that.setData({
        ['questionList[' + idx + '].value']: that.data.checkBoxList,
        ['questionList[' + idx + '].reply']: true
      });
    } else {
      that.setData({
        ['questionList[' + idx + '].value']: that.data.checkBoxList,
        ['questionList[' + idx + '].reply']: false
      });
    }
  },

  other(e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    var value = e.detail.value;
    that.setData({
      [`questionList[${idx}].other`]: value
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    //获取订单的缓存
    var orderArr = wx.getStorageSync('orderArr');
    //orderArr.id = 1;
    if (!orderArr.id) {
      app.showTip('抱歉,未获取到报名信息哦');
      setTimeout(function() {
        wx.navigateBack({
          delta: 1
        });
      }, 1500);
    } else {
      //赋值订单信息
      that.setData({
        id: orderArr.id,
        people_number: orderArr.people_number,
        sid: orderArr.sid,
        tid: orderArr.tid,
        team: orderArr.team,
        room_number: orderArr.room_number,
        remark: orderArr.remark,
        kid:orderArr.kid,
        timeInfo:orderArr.timeInfo
      });

      //清空订单信息缓存
      wx.setStorageSync('orderArr', {});
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function(res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function(res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getQuestionPageInfo(res.data.openid, orderArr);
              },
              fail: function(res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getQuestionPageInfo(openid, orderArr);
    }

    //调用分享
    that.getShareInfo();
  },


  //获取本页数据
  getQuestionPageInfo(openid, orderArr) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getQuestionPageInfo.php',
      method: 'POST',
      data: {
        openid: openid,
        id: orderArr.id,
        people_number: orderArr.people_number,
        sid: orderArr.sid,
        tid: orderArr.tid,
        kid:orderArr.kid,
        team: orderArr.team,
        room_number: orderArr.room_number,
        remark: orderArr.remark
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          that.setData({
            is_register: res.data.is_register,
            mySf: res.data.mySf,
            tipsContent: res.data.tipsContent,
            activityInfo: res.data.activityInfo,
            questionList: res.data.questionList,
            //time: res.data.time,
            //sjd: res.data.sjd
          });
        } else {
          app.showTip(res.data.msg);
          setTimeout(function() {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
      },
      fail: function() {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function() {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });

  },


  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function(res) {}
    });
  },

  //提交所有订单信息
  order() {
    var that = this;
    //判断是否注册
    if (that.data.is_register == '0') {
      wx.showModal({
        title: '温馨提示',
        content: that.data.tipsContent,
        complete: (res) => {
          if (res.confirm) {
            //跳转注册界面
            wx.setStorageSync('loginHeaderUrl', '/pages/activityCenter/detail?id=' + that.data.id + "&isType=1");
            wx.setStorageSync('loginHeaderType', 'redirectTo')
            if (res.confirm) {
              //跳转注册界面
              wx.redirectTo({
                url: '/pages/login/index'
              })
            }
          }
        }
      })
      return;
    }


    var questionList = that.data.questionList;
    var answerArr = [];
    var otherArr = [];
    for (var i = 0; i < questionList.length; i++) {
      var questionType = parseInt(questionList[i]['question_type']);
      var value = questionList[i]['value'];
      console.log("questionType:" + questionType + "......." + value)
      if (questionType == 1) {
        //选择题
        if (parseInt(value) <= 0) {
          app.showTip('请选择问题' + (i + 1) + '答案');
          return;
        } else {
          if (questionList[i].chooseList[parseInt(value) - 1].answer == "其他" || questionList[i].chooseList[parseInt(value) - 1].answer == "其它") {
            console.log(questionList[i].other)
            if (questionList[i].other == 'undefined' || questionList[i].other == undefined) {
              app.showTip('请将问题' + (i + 1) + '的其他选项的内容填写完整');
              return;
            } else {
              otherArr.push(questionList[i].other);
            }

          }
        }
      } else if (questionType == 2 && parseInt(value) < 0) {
        //数字题
        app.showTip('请填写问题' + (i + 1) + '答案');
        return;
      } else if (questionType == 3 && value == '') {
        //问答题
        app.showTip('请填写问题' + (i + 1) + '答案');
        return;
      } else if (questionType == 4) {
        //多选题
        if (value == '1') {
          app.showTip('请选择问题' + (i + 1) + '答案');
          return;
        } else {
          if (value.indexOf("其他") > -1 || value.indexOf("其它") > -1) {
            if (questionList[i].other == 'undefined' || questionList[i].other == undefined) {
              app.showTip('请将问题' + (i + 1) + '的其他选项的内容填写完整');
              return;
            } else {
              otherArr.push(questionList[i].other);
            }
          }
        }
      }

      answerArr.push(value);
    }

    //console.log(answerArr,'answerArr');
    //console.log(otherArr, 'otherArr');

    wx.showLoading({
      title: '数据提交中...'
    });


    wx.request({
      url: that.data.baseUrl + 'addBmInfoPageQuestion.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'answerArr': JSON.stringify(answerArr),
        'otherArr': JSON.stringify(otherArr),
        'id': that.data.id,
        'tid': that.data.tid,
        'sid': that.data.sid,
        'people_number': that.data.people_number,
        'team': that.data.team,
        'room_number': that.data.room_number,
        'remark': that.data.remark,
        'kid':that.data.kid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //跳转报名成功页面
          if (that.data.activityInfo.activity_type <= 2) {
            //普通活动报名或者交房预约
            wx.redirectTo({
              url: '/pages/activityCenter/bmResult?title=' + that.data.activityInfo.title + "&time=" + that.data.timeInfo + "&address=" + that.data.activityInfo.address
            });
          } else {
            //单独问卷
            app.showTip('问卷提交成功');
            setTimeout(function() {
              wx.navigateBack({
                delta: 1
              });
            }, 1500);
          }

        } else {
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function() {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        return;
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function(res) {

      },
      fail: function(res) {

      }
    }
  }
})